<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="tab-body mb-10">
        <div class="tab-box">
          <!--          //0待审核1通过2驳回3完成-->
          <el-radio-group v-model="radioStatus" size="small" @change="changeFn()" :loading="loading">
            <el-radio-button label="all" :loading="loading">全部({{ number.all }})</el-radio-button>
            <el-radio-button :label="1" :loading="loading">待用章({{ number.apply }})</el-radio-button>
            <el-radio-button :label="3" :loading="loading">已用章({{ number.adopt }})</el-radio-button>
          </el-radio-group>
        </div>
        <div class="tab-box-list">
<!--          <el-input v-model="editForm.name" auto-complete="off" placeholder="填写证照名称" size="small"-->
<!--                    class="w-140"></el-input>-->
<!--          <el-button size="small" type="primary" plain class="ml-10" @click="search('search')">搜索</el-button>-->
          <el-button size="small" plain @click="searchFn" :loading="loading">
            <i class="el-icon-refresh" v-if="!loading"></i>
            <span v-if="loading">刷新中...</span>
            <span v-else>刷新</span>
          </el-button>
        </div>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStyle.tableStripe"
              :border="tableStyle.tableBorder"
              tooltip-effect="dark"
              header-cell-class-name="table-text-c"
              :loading="loading"
              style="width: 100%">
            <el-table-column
                prop="name"
                label="公章名称"
                width="120"
                align="center"
                :ksy="1">
              <template slot-scope="scope">
                {{ scope.row.seal.name?scope.row.seal.name:'--' }}
              </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="申请人"
                width="120"
                align="center"
                :ksy="1">
              <template slot-scope="scope">
                {{ scope.row.user?scope.row.user.realname:'--' }}
              </template>
            </el-table-column>
            <el-table-column
                prop="purpose"
                label="用途"
                align="center"
                :ksy="2">
            </el-table-column>
            <el-table-column
                prop="time"
                label="用章日期"
                align="center"
                :ksy="3">
            </el-table-column>
            <el-table-column
                label="补充说明"
                prop="remark"
                align="center"
                :ksy="4">
            </el-table-column>
            <el-table-column
                prop="purpose"
                label="用章文件"
                align="center"
                :ksy="5">
              <template slot-scope="scope">
<!--                <el-button type="primary" plain @click="showFileFn(scope.row.file)" size="mini" v-if="scope.row.file && scope.row.file!=='[]'">查看用章文件</el-button>-->
                <el-popover
                  placement="left-start"
                  title="用章文件"
                  width="250"
                  trigger="click"
                  v-if="scope.row.file && scope.row.file.length">
                  <div class="tableline-li">
                    <div class="list" v-for="item in scope.row.file">
                      <preview_file :option="item" @showImg="showImg"></preview_file>
                    </div>
                  </div>
                  <el-button slot="reference" type="primary" plain size="mini">查看用章文件</el-button>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
                prop="time"
                label="盖章文件"
                align="center"
                :ksy="6">
              <template slot-scope="scope">
<!--                <viewerModle type="1" :imgSrc="scope.row.end_file" v-if="scope.row.end_file"></viewerModle>-->
                <ImagePreview :src="scope.row.end_file" width="40px" height="40px"></ImagePreview>
              </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                align="center"
                :ksy="7">
              <template slot-scope="scope">
<!--                0待审核1通过2驳回3完成 -->
                <span v-if="scope.row.status==0">待审核</span>
                <span v-if="scope.row.status==1">待用章</span>
<!--                <span v-if="scope.row.status==2">已驳回 <i>查看驳回理由</i></span>-->
                <span v-if="scope.row.status==3">已用章</span>
<!--                <span v-if="scope.row.status==4">已归还</span>-->
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="100"
                :ksy="8"
                v-if="radioStatus==1 || radioStatus=='all'">
              <template slot-scope="scope">
                <el-button type="primary" size="small" v-if="scope.row.status==1" @click="examinBtn(scope.row.id)">
                  确认用章
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <borrowOut :visible.sync="detailVisible" @InitFn="InitFn" :sealId="sealId"></borrowOut>
<!--    <previewFile :visible.sync="previewVisible" :iframeSrc="iframeSrc"></previewFile>-->
    <!--    预览-->
    <div style="position: fixed;top: -9999px">
      <viewer :images="studentPhoto" class="descimgBox">
        <img :src="studentPhoto[0]" class="viewerImg" ref="imgPrive">
      </viewer>
    </div>
  </div>
</template>

<script>
import {pagination, tableoption} from '@/utils/util.js'
import borrowOut from "./borrowOut";
// import previewFile from "@/components/modleTemplate/previewFile";
export default {
  components: {
    borrowOut,
    // previewFile
  },
  data() {
    return {
      previewVisible:false,
      detailVisible: false,
      sealId: 0,
      useType: '',
      radioStatus: 'all',
      handleSelection: [],
      arryList: [], // 页面数据列表
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      editForm: {
        name: '', // 	整型 	必填 	1 	- 	名称
      },
      number: {all: 0, apply: 0, adopt: 0}, // 初始化数量对象
      iframeSrc: '',
      studentPhoto: [],
      loading: false, // 添加loading状态
    }
  },
  created() {
    // 页面初始化时先获取总数
    this.fetchNumberData();
    // 然后获取列表数据
    this.InitFn()
  },
  methods: {
    // 获取数量数据
    fetchNumberData() {
      this.loading = true;
      // 分别请求三个接口获取不同状态的数据
      const promises = [
        // 请求全部状态的数据
        this.$fetch(this.api.seal.apply_list, { page: 1, limit: 1 }),
        // 请求待用章状态的数据
        this.$fetch(this.api.seal.apply_list, { status: 1, page: 1, limit: 1 }),
        // 请求已用章状态的数据
        this.$fetch(this.api.seal.apply_list, { status: 3, page: 1, limit: 1 })
      ];

      return Promise.all(promises)
        .then((responses) => {
          // 从各个接口响应中提取total字段
          const allTotal = responses[0].code === 0 ? responses[0].list.total : 0;
          const applyTotal = responses[1].code === 0 ? responses[1].list.total : 0;
          const adoptTotal = responses[2].code === 0 ? responses[2].list.total : 0;
          
          // 设置数量统计数据
          this.number = {
            all: allTotal,
            apply: applyTotal,
            adopt: adoptTotal
          };
        })
        .catch((err) => {
          console.log('获取数量数据失败:', err);
          // 发生错误时，设置默认值
          this.number = {all: 0, apply: 0, adopt: 0};
        })
        .finally(() => {
          // fetchNumberData不负责管理loading状态，由调用它的函数管理
        });
    },
    
    // 初始化
    InitFn() {
      this.loading = true; // 开始加载时显示loading
      // type 2 审核人员 1 借用管理
      let option_ = {p: this.page.pageindex, type: 1, name: this.editForm.name}
      if (this.radioStatus !== 'all') {
        option_.status = this.radioStatus;
      }
      // <!--                // 0待审核1通过2驳回3借出4归还-->  
      // <!--                申请通过 已驳回 待归还 已归还   -->
      return this.$fetch(this.api.seal.apply_list, option_).then((response) => {
        if (response.code === 0) {
          console.log('response==>', response)
          // 安全地处理文件数据
          if (Array.isArray(response.list.data)) {
            for(let item of response.list.data){
              if(item.file && typeof item.file === 'string'){
                try {
                  if(item.file.indexOf('[')!==-1){
                    item.file = JSON.parse(item.file)
                  }else{
                    item.file = [{name:'文件1', src: item.file}]
                  }
                } catch (e) {
                  console.error('文件数据解析失败:', e);
                  item.file = [];
                }
              } else {
                item.file = [];
              }
            }
          }
          this.arryList = response.list.data || []
          this.page.total = response.list.total || 0
          
          // 移除自动更新number数据的逻辑，避免与fetchNumberData方法的数据冲突
          // 数量统计数据由专门的fetchNumberData方法管理
        } else {
          // 接口返回错误时，清空列表数据
          this.arryList = [];
          this.page.total = 0;
        }
      }).catch((err) => {
        console.log('获取列表数据失败:', err);
        // 请求失败时，清空列表数据
        this.arryList = [];
        this.page.total = 0;
      }).finally(() => {
        this.loading = false; // 无论成功失败都隐藏loading
      })
    },
    search(option) {
      this.page.pageindex = 1;
      if (option !== 'search') {
        this.editForm.name = '';
      }
      
      // 使用Element UI的Loading组件显示全屏加载效果
      const loadingInstance = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 搜索时同时更新数量统计
      this.fetchNumberData()
        .then(() => {
          return this.InitFn();
        })
        .finally(() => {
          // 确保在所有操作完成后关闭loading
          loadingInstance.close();
        });
    },
    examinBtn(id) {
      // 1 确认借出 2 提醒归还 3 确认归还
      this.sealId = id;
      this.detailVisible = true
    },
    showImg(option){
      console.log('option:', option)
      this.$set(this.studentPhoto, 0, option[0])
      setTimeout(()=>{
        this.$refs.imgPrive.click()
      }, 100)
    },
    changeFn() {
      // 使用Element UI的Loading组件显示全屏加载效果
      const loadingInstance = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 切换标签时同时更新数量统计
      this.fetchNumberData()
        .then(() => {
          return this.InitFn();
        })
        .finally(() => {
          // 确保在所有操作完成后关闭loading
          loadingInstance.close();
        });
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      
      // 使用Element UI的Loading组件显示全屏加载效果
      const loadingInstance = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      this.InitFn()
        .finally(() => {
          // 确保在数据加载完成后关闭loading
          loadingInstance.close();
        });
    },
    // 搜索组件
    searchFn(option) {
      this.page.pageindex = 1
      // this.searchForm = option
      
      // 使用Element UI的Loading组件显示全屏加载效果
      const loadingInstance = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 刷新时同时更新数量统计
      this.fetchNumberData()
        .then(() => {
          return this.InitFn();
        })
        .finally(() => {
          // 确保在所有操作完成后关闭loading
          loadingInstance.close();
        });
    },
    // 借出
    async lendLicence(id) {
      this.loading = true;
      try {
        let data = await this.$post(this.api.licence.receive, {id: id});
        console.log('借出成功：', data)
        if (!data.code) {
          // 操作成功后更新数量统计和列表数据
          await this.fetchNumberData();
          this.InitFn();
        }
      } catch (err) {
        console.log('借出失败:', err);
        this.$message.error('借出失败！');
      } finally {
        this.loading = false;
      }
    },
    // 提醒归还
    async remindLicence(id) {
      this.loading = true;
      try {
        let data = await this.$post(this.api.licence.remind, {id: id});
        console.log('提醒成功：', data)
        if (!data.code) {
          this.$message.success('提醒成功！');
          // 操作成功后更新数量统计和列表数据
          await this.fetchNumberData();
          this.InitFn();
        }
      } catch (err) {
        console.log('提醒失败:', err);
        this.$message.error('提醒失败！');
      } finally {
        this.loading = false;
      }
    },
    subimitExamin(type, id, value) {
      this.loading = true; // 开始加载时显示loading
      let n = this;
      let option = {id: id, type: type}
      if (type === 2) {
        option.content = value;
      }
      this.$post(this.api.licence.examine, option).then((response) => {
        if (response.code === 0) {
          // 操作成功后更新数量统计和列表数据
          this.fetchNumberData().then(() => {
            n.InitFn()
          });
        } else {
        }
      }).catch((err) => {
        console.log('提交审核失败:', err)
        this.loading = false; // 失败时也隐藏loading
      })
    },
    showFileFn(fileSrc) {
      if(fileSrc && typeof fileSrc === 'string' && fileSrc!=='[]'){
        try {
          let file = JSON.parse(fileSrc);
          if(file && Array.isArray(file) && file.length > 0 && file[0].src){
            this.iframeSrc = file[0].src;
            this.previewVisible = true;
          }
        } catch (e) {
          console.error('文件解析失败:', e);
        }
      }
    }
  },
  mounted() {
  },
  // 缓存机制 end
}
</script>

<style scoped>

.wx-user-box-line img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 5px;
}

.wx-user-box-line {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-wx {
  cursor: pointer;
  padding: 5px;
}

.btn-wx:hover {
  color: #1b8de5;
  text-decoration: underline;
}

.delet-wx {
  color: red;
  cursor: pointer;
}

.delet-wx:hover {
  text-decoration: underline;
}

.tab-body {
  display: flex;
  align-items: center;
}

.tab-box {
  flex: 1;
}

.tab-box-list {
  display: flex;
  align-items: center;
}
</style>
